<template>
  <a-card>
    <!-- 表格区域 -->
    <div class="operator">
      <a-button v-permission="'system:menu:add'" class="mr-8" type="primary" @click="handleAdd"
        >新增</a-button
      >
      <!-- <a-button class="mr-8" type="primary" @click="handleAdd">新增</a-button> -->
    </div>
    <a-table
      bordered
      :loading="loading"
      :pagination="false"
      :columns="columns"
      :row-key="item => item.id"
      :data-source="dataSource"
      :indentSize="10"
    >
      <span slot="icon" slot-scope="icon">
        <a-icon :type="icon" />
      </span>

      <span slot="type" slot-scope="type">
        <a-tag color="green" v-if="type === 0">目录</a-tag>
        <a-tag color="orange" v-else-if="type === 1">菜单</a-tag>
        <a-tag color="cyan" v-else-if="type === 2">按钮</a-tag>
      </span>

      <span slot="action" slot-scope="item">
        <a v-permission="'system:menu:update'" @click="handleEdit(item)">修改</a>
        <a-divider type="vertical" />
        <a v-permission="'system:menu:del'" style="color: #ff4d4f" @click="handleDel(item)">删除</a>
      </span>
    </a-table>

    <!-- 新增/修改弹窗 -->
    <a-modal
      :title="modalTitle"
      :visible="visible"
      :maskClosable="false"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form
        :form="form"
        :labelCol="formItemLayout.labelCol"
        :wrapperCol="formItemLayout.wrapperCol"
      >
        <a-form-item label="类型">
          <a-radio-group
            v-decorator="[
              'type',
              {
                initialValue: 1,
                rules: [{ required: true }],
              },
            ]"
          >
            <a-radio :value="0">目录</a-radio>
            <a-radio :value="1">菜单</a-radio>
            <a-radio :value="2">按钮</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item label="目录名称" v-show="form.getFieldValue('type') === 0">
          <a-input
            v-decorator="[
              'name',
              {
                rules: [
                  {
                    required: true,
                    message: '目录名称不能为空',
                  },
                ],
              },
            ]"
            placeholder="请输入目录名称"
          />
        </a-form-item>

        <a-form-item label="菜单名称" v-show="form.getFieldValue('type') === 1">
          <a-input
            v-decorator="[
              'name',
              {
                rules: [
                  {
                    required: true,
                    message: '菜单名称不能为空',
                  },
                ],
              },
            ]"
            placeholder="请输入菜单名称"
          />
        </a-form-item>

        <a-form-item label="路由" v-if="form.getFieldValue('type') !== 2">
          <a-input
            v-decorator="[
              'url',
              {
                rules: [
                  {
                    required: true,
                    message: '菜单路由不能为空',
                  },
                ],
              },
            ]"
            placeholder="请输入菜单路由"
          />
        </a-form-item>

        <a-form-item label="按钮名称" v-show="form.getFieldValue('type') === 2">
          <a-input
            v-decorator="[
              'name',
              {
                rules: [
                  {
                    required: true,
                    message: '按钮名称不能为空',
                  },
                ],
              },
            ]"
            placeholder="请输入按钮名称"
          />
        </a-form-item>

        <a-form-item label="上级菜单">
          <a-tree-select
            v-decorator="[
              'parentId',
              {
                initialValue: -1,
                rules: [
                  {
                    required: true,
                    message: '上级菜单不能为空',
                  },
                ],
              },
            ]"
            style="width: 100%"
            :dropdown-style="{
              maxHeight: '400px',
              overflow: 'auto',
            }"
            :tree-data="treeData"
            :treeDefaultExpandedKeys="[-1]"
          >
          </a-tree-select>
        </a-form-item>

        <a-form-item label="授权标识" v-show="form.getFieldValue('type') !== 0">
          <a-input
            v-decorator="['perms']"
            placeholder="多个用逗号隔开， 如：user:list,user:create"
          />
        </a-form-item>

        <a-form-item label="排序号">
          <a-input-number v-decorator="['orderNum']" size="large" :min="1" :max="100000" />
        </a-form-item>

        <a-form-item label="图标" v-show="form.getFieldValue('type') === 0">
          <a-input v-decorator="['icon']" placeholder="请输入" />
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script>
import { systemService } from '@/services';

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    align: 'center',
    width: 150,
  },
  {
    title: '名称',
    dataIndex: 'name',
    key: 'name',
    align: 'center',
    width: 150,
  },
  {
    title: '图标',
    key: 'icon',
    dataIndex: 'icon',
    scopedSlots: { customRender: 'icon' },
    align: 'center',
    width: 150,
  },
  {
    title: '类型',
    key: 'type',
    dataIndex: 'type',
    scopedSlots: { customRender: 'type' },
    align: 'center',
    width: 150,
  },
  {
    title: '排序号',
    key: 'orderNum',
    dataIndex: 'orderNum',
    align: 'center',
    width: 100,
  },
  {
    title: '菜单URL',
    key: 'url',
    dataIndex: 'url',
    align: 'center',
  },
  {
    title: '授权标识',
    key: 'perms',
    dataIndex: 'perms',
    align: 'center',
  },
  {
    title: '操作',
    key: 'action',
    scopedSlots: { customRender: 'action' },
    align: 'center',
    width: 150,
  },
];

const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};

export default {
  name: 'systemMenu',

  data() {
    return {
      menuTree: null,
      columns,
      dataSource: [],
      loading: false,
      visible: false,
      type: 1, // 1-新增 2-修改
      formItemLayout,
      form: this.$form.createForm(this, { name: 'menu-form' }),
      treeData: [], // 弹窗的树形选择
      confirmLoading: false,
      selectedItem: null,
    };
  },

  computed: {
    modalTitle() {
      return this.type === 1 ? '新增' : '修改';
    },

    formType() {
      const type = this.form.getFieldValue('type');
      return type;
    },

    formNameLabel() {
      const labelMap = ['目录名称', '菜单名称', '按钮名称'];
      return labelMap[this.formType];
    },
  },

  created() {
    this.$nextTick(() => {
      this.form.setFieldsValue({ type: 1 });
    });
    this.getDataSource();
  },

  methods: {
    // 获取数据
    getDataSource() {
      this.loading = true;
      systemService.getMenuTree().then(res => {
        if (res.code === '200') {
          this.dataSource = res.data.rootNode.children;
          this.treeData = this.formatTreeData(res.data.rootNode);
          this.loading = false;
        }
      });
    },

    // 处理菜单树
    formatTreeData(rootNode) {
      console.log(rootNode);
      const second =
        rootNode.children && rootNode.children.length
          ? rootNode.children.map(item => {
              return {
                title: item.name,
                value: item.id,
                key: item.id,
                children:
                  item.children && item.children.length
                    ? item.children.map(subItem => {
                        return {
                          title: subItem.name,
                          value: subItem.id,
                          key: subItem.id,
                        };
                      })
                    : null,
              };
            })
          : null;
      return [
        {
          title: '一级菜单',
          value: rootNode.id,
          key: rootNode.id,
          children: second,
        },
      ];
    },

    // 新增
    handleAdd() {
      this.type = 1;
      this.visible = true;
    },

    // 删除
    handleDel(item) {
      console.log(item);
      const that = this;
      this.$confirm({
        title: '确认删除该菜单吗？',
        content: () => <div style='color:red;'>删除后不可恢复！</div>,
        okText: '删除',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          const { id } = item;
          console.log(id);
          return new Promise(resolve => {
            systemService
              .delMenu({ id })
              .then(res => {
                console.log(res);
                if (res.code === '200') {
                  that.$message.success('删除成功');
                  that.getDataSource(that.pagination);
                }
              })
              .finally(() => resolve());
          });
        },
        onCancel() {
          console.log('Cancel');
        },
      });
    },

    // 修改
    handleEdit(item) {
      console.log(item.perms);
      this.type = 2;
      this.visible = true;
      this.selectedItem = item;
      this.$nextTick(() => {
        if (item.type == 0) {
          this.form.setFieldsValue({
            type: item.type,
            name: item.name,
            url: item.url,
            parentId: item.parentId,
            orderNum: item.orderNum,
            icon: item.icon,
          });
        } else if (item.type === 1) {
          this.form.setFieldsValue({
            type: item.type,
            name: item.name,
            parentId: item.parentId,
            orderNum: item.orderNum,
            url: item.url,
            perms: item.perms,
          });
        } else {
          this.form.setFieldsValue({
            type: item.type,
            name: item.name,
            parentId: item.parentId,
            orderNum: item.orderNum,
            perms: item.perms,
          });
        }
      });
    },

    // 取消新建
    handleCancel() {
      this.visible = false;
      this.selectedItem = null;
      this.form.resetFields();
    },

    // 新建/修改确认
    handleOk() {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.confirmLoading = true;
          console.log('Received values of form: ', values);
          if (this.type === 1) {
            systemService
              .addMenu(values)
              .then(res => {
                console.log(res);
                if (res.code === '200') {
                  this.$message.success('操作成功');
                  this.visible = false;
                  this.form.resetFields();
                  this.getDataSource();
                }
              })
              .catch(e => {
                this.$message.error(e);
              })
              .finally(() => {
                this.confirmLoading = false;
              });
          } else {
            systemService
              .updateMenu({ ...values, id: this.selectedItem.id })
              .then(res => {
                console.log(res);
                if (res.code === '200') {
                  this.$message.success('操作成功');
                  this.visible = false;
                  this.selectedItem = null;
                  this.form.resetFields();
                  this.getDataSource();
                }
              })
              .catch(e => {
                this.$message.error(e);
              })
              .finally(() => {
                this.confirmLoading = false;
              });
          }
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.operator {
  margin-bottom: 24px;
}
</style>
